package co.fitstart.admin.web.controller.report;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Page;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.report.ReportPrepare;
import co.fitstart.admin.entity.report.RevenueReportStatistics;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.ReportService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.report.RevenueReport;
import co.fitstart.entity.site.Site;

@Controller
@RequestMapping("/revenue-reports")
@MenuSetting("menu-report")
public class RevenueReportController {
    
    @Autowired
    private SiteService siteService;
    
    @Autowired
    private ReportService reportService;
    
    @Autowired
    private PrincipalService principalService;
    
    /**
     * 
     * @param login
     * @param siteId
     * @param date
     * @param period
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-revenue-report")
    public ModelAndView list(@Secure Login login,
                             @RequestParam(name = "site", required = false) Long siteId,
                             @RequestParam(name = "date", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
                             @RequestParam(name = "period", required = false, defaultValue = "day") String period) {
        
        ModelAndView modelAndView = new ModelAndView("report/revenue-report-list");
        
        Site site = null;
        if(login.hasSite()) {
            site = login.getSite();
        } else if(siteId != null) {
            site = siteService.load(siteId);
        }
        
        ReportPrepare reportPrepare = new ReportPrepare(site, date, period);
        modelAndView.addAllObjects(reportPrepare.describeReport());
        
        Map<String, Map<String, Map<String, Long>>> reports = new HashMap<>();
        Map<String, Long> statistics = new HashMap<>();
        
        if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                if(siteId == null) {
                    reports = reportService.listRevenueReportStatistics(sites, reportPrepare.getCurrentDate(), period);
                    statistics = reportService.getRevenueTotal(sites, date, period);
                } else if(site != null && sites.contains(site)) {
                    reports = reportService.listRevenueReportStatistics(site, reportPrepare.getCurrentDate(), period);
                    statistics = reportService.getRevenueTotal(site, date, period);
                }
                
            }
        } else {
            reports = reportService.listRevenueReportStatistics(site, reportPrepare.getCurrentDate(), period);
            statistics = reportService.getRevenueTotal(site, reportPrepare.getCurrentDate(), period);
        }
        
        modelAndView.addObject("reports", reports);
        
        modelAndView.addObject("statistics", statistics);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param date
     * @param site
     * @param request
     * @param page
     * @return
     */
    @RequestMapping("/grid")
    public ModelAndView grid(@Secure Login login,
                             @RequestParam(value = "date", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date date, 
                             @RequestParam(value = "site", required = false) Long siteId,
                             @RequestParam(name = "period", required = false, defaultValue = "day") String period,
                             HttpServletRequest request,
                             Page page) {
       
        ModelAndView modelAndView = new ModelAndView("report/revenue-report-grid");
        
        Site site = null;
        if(login.hasSite()) {
            site = login.getSite();
        } else if(siteId != null) {
            site = siteService.load(siteId);
        }
        
        List<RevenueReport> revenueReports = new ArrayList<>();
        
        if(site == null && (login.isAreaManager() || login.isAreaServer())) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                revenueReports = reportService.listRevenueReport(sites, date, period, page);
            }
        } else {
            revenueReports = reportService.listRevenueReport(site, date, period, page);
        }
        
        modelAndView.addObject("revenueReports", revenueReports);
        modelAndView.addObject("total", revenueReports.size());
        
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "list");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/export-view", method = RequestMethod.GET)
    public ModelAndView export() {
        
        ModelAndView modelAndView = new ModelAndView("report/revenue-report-export");
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param view
     * @param siteId
     * @param beginDate
     * @param endDate
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView onExport(@Secure Login login,
                                 @RequestParam(value = "site" , required = false) Long siteId,
                                 @RequestParam(value = "beginDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginDate,
                                 @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("revenue-report.xls"));
        
        // get site
        Site site = null;
        if(login.hasSite()) {
            site = login.getSite();
        } else if(siteId != null) {
            site = siteService.load(siteId);
        }
        
        Map<String, Map<String, Map<String, RevenueReportStatistics>>> reports = new HashMap<>();
        List<RevenueReport> reveueReports = new ArrayList<>();
        
        if(login.isAreaManager() || login.isAreaServer()) {
            Principal areaManager = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(areaManager);
            
            if(!sites.isEmpty()) {
                if(siteId == null) {
                    reports = reportService.listRevenueReportStatistics(sites, beginDate, endDate);
                    reveueReports = reportService.listRevenueReport(site, beginDate, endDate);
                } else if(site != null && sites.contains(site)) {
                    reports = reportService.listRevenueReportStatistics(site, beginDate, endDate);
                    reveueReports = reportService.listRevenueReport(site, beginDate, endDate);
                }
                
            }
        } else {
            reports = reportService.listRevenueReportStatistics(site, beginDate, endDate);
            reveueReports = reportService.listRevenueReport(site, beginDate, endDate);
        }
        
        
        modelAndView.addObject("reports", reports);
        modelAndView.addObject("revenueReports", reveueReports);
        
        Map<String, Long> statistics = reportService.getRevenueTotal(reports);
        modelAndView.addObject("statistics", statistics);
        
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        modelAndView.addObject("fmt", fmt);
        
        NumberFormat numFmt = new DecimalFormat("0");
        modelAndView.addObject("numFmt", numFmt);
        
        return modelAndView;
    }

}
